package com.probox.common.core.utils;

import cn.hutool.core.util.ObjectUtil;

import java.util.Arrays;
import java.util.HashMap;

/**
 * @Description
 * @Author Yaze
 * @Date Created in 2022/3/15
 */
public class SplitUtils {

    /**
     * 拆分并且转换为数据字典的code
     *
     * @param str
     * @param map
     * @return
     */
    public static String splitStr(String str, HashMap map) {
        StringBuffer buffer = new StringBuffer();
        if (ObjectUtil.isNotEmpty(str)) {
            String[] split = str.split(",");
            if (ObjectUtil.isEmpty(split)) return buffer.toString();
            Arrays.stream(split).forEach(s -> {
                Object o = map.get(s);
                if (ObjectUtil.isNotEmpty(o)) {
                    buffer.append(o + ",");
                }
            });
        }
        String string = buffer.toString();
        if (ObjectUtil.isEmpty(string.toString())) return "";
        return string.substring(0, string.length() - 1);
    }


    public static String isVideo(String resource) {
        String[] arr = resource.split(",");
        if (arr.length > 1) {
            return arr[0];
        } else {
            String[] split = resource.split(".com/");
            if (split[1].indexOf(".") > -1) {
                boolean isImage = isImage(split[1]);
                if (!isImage) {
                    return resource + "?vframe/jpg/offset/0";
                } else {
                    return arr[0];
                }
            } else {
                return arr[0];
            }
        }
    }

    public static String isVideoType(String resource) {
        String[] arr = resource.split(",");
        if (arr.length > 1) {
            return "img";
        } else {
            String[] split = resource.split(".com/");
            if (split[1].indexOf(".") > -1) {
                boolean isImage = isImage(split[1]);
                if (!isImage) {
                    return "video";
                } else {
                    return "img";
                }
            } else {
                return "img";
            }
        }
    }

    private final static String[] imageExt = {".bmp", ".jpg", ".png", ".tif", ".gif", ".svg", ".webp", ".avif", ".apng"};

    public static boolean isImage(String file) {
        String fileName = file.toLowerCase();
        boolean rst = false;
        for (String ext : imageExt) {
            if (fileName.indexOf(ext) > 0) {
                return true;
            }
        }
        return rst;
    }

}
